var xlsx = require('node-xlsx');
var fs = require('fs');
var moment = require('moment');


// excel小数时间中 1表示一天  所以小数转换成秒 需要 * 24 *60 * 60
// 9:00:00的小数表示 上班
// var timeOn = 0.375;
var timeOn = 0.37569444444444444
    // 18:00:00的小数表示 下班
var timeOff = 0.75;

var timeOvertime = 0.875;
var timeOverTimeCar = 0.9583333333333334;

var weekdayNames = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];

var late1 = 0.38263888888888886;
var late2 = 0.38958333333333334;
var late3 = 0.39652777777777776;

var getMoment = function(num) {
    var start = moment('1900-01-01', 'YYYY-MM-DD');
    var result = start.add(num - 2, 'd');
    return result;
};

var getTime = function(fl) {
    var h = fl * 24;
    var H = Math.floor(h);
    var m = (h - H) * 60;
    var M = Math.floor(m);
    var s = (m - M) * 60;
    var S = Math.floor(s);
    var str = '';
    if (H < 10) {
        str += '0';
    }
    str += H + ':';
    if (M < 10) {
        str += '0';
    }
    str += M + ':';
    if (S < 10) {
        str += '0';
    }
    str += S.toFixed();
    return str;
}


// var whiteList = ['温总', '温伟林', '段俊'];
// 获取本月的工作日
// var getWorkDayArr = function(mm) {
//     var days = mm.daysInMonth();
//     var day = moment(mm.format('YYYY-MM' + '-01'));

//     var workDayArr = [];
//     for (var i = 0; i < days; i++) {
//         if (isWorkDay(day)) {
//             workDayArr.push(day.date());
//         }
//         day.add(1, 'd');
//     }
//     console.log('最后一天是：' + day.format('YYYY-MM-DD'));
//     return workDayArr;
// }

function isWorkDay(day) {
    var weekday = day.weekday();
    if (weekday >= 1 && weekday <= 5) {
        return true;
    } else {
        return false;
    }
}


module.exports = function(filePath, whiteList, workdays, selectMonthStr, callback, failCallback) {
    var filterWhite = function(name) {
        return whiteList.indexOf(name) >= 0;
    };

    var obj = xlsx.parse(filePath); //配置excel文件的路径
    var sheet1 = obj[0];
    var nameMap = {};
    var nameIndex = [];
    var monthMoment = getMoment(sheet1.data[1][1]);
    var monthMomentFormat = monthMoment.format('YYYY-MM');
    if (monthMomentFormat != selectMonthStr) {
        if (monthMomentFormat == '1900-01') {
            failCallback("打卡记录格式不正确，请检查文件是否有误！")
        } else {
            failCallback("请重新设置工作日，所选Excel文件为" + monthMoment.format('YYYY年MM月'))
        }
        return;
    }
    var workDayArr = workdays;
    for (var index = 1; index < sheet1.data.length; index++) {
        var element = sheet1.data[index];
        var name = element[0];
        if (!filterWhite(name)) {
            if (!nameMap[name]) {
                nameMap[name] = [];
                nameIndex.push(name);
            }
            nameMap[name].push(element);
        }
    }

    var workdayRecordsMap = {};

    for (var element in nameMap) {
        if (nameMap.hasOwnProperty(element)) {
            // arr 为 一个月内的打卡记录数组
            var arrs = nameMap[element];

            var dayMap = {};

            for (var index = 0; index < arrs.length; index++) {
                var e = arrs[index];
                var day = e[1];
                if (!dayMap[day]) {
                    dayMap[day] = [];
                    dayMap[day][0] = e;
                } else {
                    dayMap[day][1] = e;
                }
            }

            var workdayRecords = [];
            for (var key in dayMap) {
                if (dayMap.hasOwnProperty(key)) {
                    var e = dayMap[key];
                    var on = e[0];
                    var off = e[1];
                    var date = getMoment(key);

                    var dayResult = {
                        'late': false, //迟到
                        'forget': false, //上班漏打卡/下班漏打卡/请假
                        'absent': false, //缺勤
                        'overtime': false, //加班到9点
                        'overtimeCar': false, //加班到11点，车补
                        'overtimeDay': false, //非工作日加班
                        'recordOn': on,
                        'recordOff': off,
                        'name': element
                    };
                    workdayRecords[date.date() - 1] = dayResult;


                    // 是工作日
                    if (workDayArr.indexOf(date.date()) >= 0) {
                        var startTime = on[3];
                        if (startTime > timeOn) {
                            if (startTime <= late1) {
                                dayResult.late = 10;
                            } else if (startTime <= late2) {
                                dayResult.late = 20;
                            } else if (startTime <= late3) {
                                dayResult.late = 50;
                            } else {
                                //上班时间超过了9:30，可能需要请假
                                dayResult.forget = true;
                            }
                        }
                        // 如果一天只有一次打卡，那么这次打卡也可能是下班打卡
                        if (!off) {
                            off = on;
                            dayResult.forget = true;
                        }
                        var endTime = off[3];
                        if (endTime < timeOff) {
                            dayResult.forget = true;
                        } else if (endTime >= timeOverTimeCar) {
                            dayResult.overtimeCar = true;
                        } else if (endTime >= timeOvertime) {
                            dayResult.overtime = true;
                        }
                    } else {
                        dayResult.overtimeDay = true;
                    }
                }
            }
            for (var index = 0; index < workDayArr.length; index++) {
                var workday = workDayArr[index];
                if (!workdayRecords[workday - 1]) {
                    var workdayMoment = moment(monthMoment.format('YYYY-MM-01')).add(workday - 1, 'd');
                    var weekdayName = weekdayNames[workdayMoment.weekday() - 1];
                    workdayRecords[workday - 1] = {
                        'absent': true,
                        'name': element,
                        'date': workdayMoment.format('MM-DD'),
                        'weekday': weekdayName,
                        'moment': workdayMoment
                    };
                }

            }
            workdayRecordsMap[element] = workdayRecords;
        }
    }

    var data = [];

    var workdayRecordsNameList = [];
    for (var index = 0; index < nameIndex.length; index++) {
        var element = nameIndex[index];
        workdayRecordsNameList.push(workdayRecordsMap[element]);
    }

    var lateData = [];
    var forgetData = [];
    var absentData = [];
    var overtimeData = [];
    var overtimeCarData = [];
    var overtimeDayData = [];

    var lateMap = {};
    workdayRecordsNameList.forEach(function(element) {
        var lateDataLength = lateData.length;
        var forgetDataLength = forgetData.length;
        var absentDataLength = absentData.length;
        var overtimeDataLength = overtimeData.length;
        var overtimeCarDataLength = overtimeCarData.length;
        var overtimeDayDataLength = overtimeDayData.length;

        element.forEach(function(dayResult) {
            var record = [];
            if (dayResult.recordOn) {
                var name = dayResult.recordOn[0];
                var date = getMoment(dayResult.recordOn[1]).format('MM-DD');
                var weekday = dayResult.recordOn[2];
                var onTime = getTime(dayResult.recordOn[3]);
                record = [name, date, weekday, onTime];
                if (dayResult.recordOff) {
                    var offTime = getTime(dayResult.recordOff[3]);
                    record.push(offTime);
                }
            } else {
                record = [];
            }
            if (dayResult.late) {
                var copy = record.concat();
                var name = copy[0];
                if (!lateMap[name]) {
                    lateMap[name] = 0;
                }
                var late = dayResult.late;
                if (late == 10) {
                    lateMap[name]++;
                    if (lateMap[name] > 3) {
                        copy[5] = late;
                    } else {
                        copy[5] = 0;
                    }
                } else {
                    copy[5] = late;
                }
                lateData.push(copy);
            }
            if (dayResult.forget) {
                forgetData.push(record);
            }
            if (dayResult.overtime) {
                overtimeData.push(record);
            }
            if (dayResult.overtimeCar) {
                overtimeCarData.push(record);
            }
            if (dayResult.overtimeDay) {
                overtimeDayData.push(record);
            }
            if (dayResult.absent) {
                record = [dayResult.name, dayResult.date, dayResult.weekday];
                absentData.push(record);
            }
        });

        if (lateData.length > lateDataLength) {
            lateData.push([]);
        }
        if (forgetData.length > forgetDataLength) {
            forgetData.push([]);
        }
        if (absentData.length > absentDataLength) {
            absentData.push([]);
        }
        if (overtimeData.length > overtimeDataLength) {
            overtimeData.push([]);
        }
        if (overtimeCarData.length > overtimeCarDataLength) {
            overtimeCarData.push([]);
        }
        if (overtimeDayData.length > overtimeDayDataLength) {
            overtimeDayData.push([]);
        }
    });
    var buffer = xlsx.build([{
        name: '迟到半小时内',
        data: lateData
    }, {
        name: '上班漏打卡_下班漏打卡_请假',
        data: forgetData
    }, {
        name: '缺勤',
        data: absentData
    }, {
        name: '加班到9点',
        data: overtimeData
    }, {
        name: '加班到11点',
        data: overtimeCarData
    }, {
        name: '非工作日加班',
        data: overtimeDayData
    }]);


    var destPath = filePath.split('\\');
    destPath.pop();
    destPath.push('考勤结果_' + monthMoment.format('YYYYMM') + '_' + moment().format('YYYYMMDDHHmmss') + '.xlsx')
    destPath = destPath.join('\\');
    fs.writeFileSync(destPath, buffer, { 'flag': 'w' });
    callback(destPath);
}